import api from './api/api'
console.log(api.tologin)
App({
  onLaunch: function (opitions) {
    let self = this
  },
  // getSetting(cb) {
  //     let self = this
  // },
  getApi: api,
  getToken(cb) {
    let self = this
    if (self.globalData.token) {
      if (typeof cb == 'function') {
        cb(self.globalData.token);
      }
    } else {
      wx.login({
        success(res) {
          var code = res.code; //得到code
          api.tologin({ wx_code: code }).then(res1 => {
            if (res1.code == "3002") {
              console.log('登录获取token=>', res1)
              self.globalData.openid = res1.data.openid
              self.globalData.token = res1.data.token || 'g5w76maEhkrWe//eNq41DQ==' //res1.data.token
              typeof cb == 'function' && cb(res1.data.token)
            } else {
              console.log('登录失败===>', res1.message)
            }
          }).catch(Error => {
            console.log('登录失败', Error)
          })
        }
      })
    }
  },
  getUserInfoNext(cb) {
    let self = this
    self.getUserInfo().then(res2 => {
      typeof cb == 'function' && cb() //首次进入
      self.globalData.userInfo = res2.userInfo;
    }).catch(userError => {
      console.log('首次进入', userError)
      if (
        userError.errMsg == 'getUserInfo:fail scope unauthorized' ||
        userError.errMsg == 'getUserInfo:fail auth deny' ||
        userError.errMsg == 'getUserInfo:fail:scope unauthorized' ||
        userError.errMsg == 'getUserInfo:fail:auth deny'
      ) {
        typeof cb == 'function' && cb() //首次进入
        wx.navigateTo({
          url: `../accredit/index`
        });
      }
    })
  },
  getUserInfo() {
    return new Promise(function (resolve, reject) {
      wx.getUserInfo({
        success(res) {
          console.log('成功获取用户信息代表已经授权',res)
          resolve(res)
        },
        fail(error) {
          console.log('用户没有授权过信息',error)
          reject(error)
        }
      })
    })
  },
  globalData: {
    userInfo: null,
    token: '',
    scaning: false
  }
})